package com.fzn3.day05;

/**
 * @author fzn
 * 描述：杨辉三角-优化  一维数组
 * @program DataStructure
 * @create 2023/3/10 10:49
 **/
public class PascalTriangle3 {
    private static int element(int[][] triangle, int i, int j) {
        // 记录过了就直接返回
        if (triangle[i][j] > 0) {
            return triangle[i][j];
        }
        if (j == 0 || i == j) {
            triangle[i][j] = 1;
            return 1;
        }
        triangle[i][j] = element(triangle, i - 1, j - 1) + element(triangle, i - 1, j);
        return triangle[i][j];
    }

    private static void printSpace(int n, int i) {
        int num = (n - 1 - i) * 2;
        for (int j = 0; j < num; j++) {
            System.out.print(" ");
        }
    }

    public static void print(int n) {
        int[] row = new int[n];
        for (int i = 0; i < n; i++) {
            createRow(row, i);
            printSpace(n, i);
            for (int j = 0; j <= i; j++) {
                System.out.printf("%-4d", row[j]);
            }
            System.out.println();
        }
    }


    /**
     * 创建行
     *
     * @param row 行
     * @param i   行号
     */
    private static void createRow(int[] row, int i) {
        if (row[i] > 0) {
            // 如果这一行的数据计算过了 直接返回
            return;
        }
        if (i == 0) {
            row[0] = 1;
            return;
        }
        createRow(row, i - 1); // 计算结果存入row
        for (int j = i; j > 0; j--) {
            row[j] += row[j - 1];
        }
    }

    public static void main(String[] args) {
        print(5);
    }
}
